package baoycode.utils;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ContainerSelectionDialog;

public class ViewCreator {

	public static Text createText(Composite container, String textName) {
		Label label = new Label(container, SWT.LEFT);
		GridData labelStyle = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		labelStyle.widthHint = 80;
		label.setLayoutData(labelStyle);
		label.setText(textName);
		Text text = new Text(container, SWT.BORDER);
		text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		new Label(container, SWT.NONE);
		return text;
	}

	public static Button createButton(Composite parent, String text, int width) {
		Button btn = new Button(parent, SWT.NONE);
		GridData gd = new GridData(SWT.LEFT, SWT.CENTER, false, true, 1, 1);
		gd.widthHint = width;
		btn.setLayoutData(gd);
		btn.setText(text);
		return btn;
	}

	public static class BrowseSelectionAdapter extends SelectionAdapter {
		private final String title;
		private final Text text;
		private final Shell shell;

		public BrowseSelectionAdapter(Shell shell, String title, Text text) {
			this.shell = shell;
			this.title = title;
			this.text = text;
		}

		@Override
		public void widgetSelected(SelectionEvent e) {
			ContainerSelectionDialog dialog = new ContainerSelectionDialog(this.shell,
					ResourcesPlugin.getWorkspace().getRoot(), false, title);
			if (dialog.open() == ContainerSelectionDialog.OK) {
				Object[] result = dialog.getResult();
				if (result.length == 1) {
					text.setText(((Path) result[0]).toString());
				}
			}
		}
	}
}
